//
//  BOSSSoundWaveController.m
//  Pay
//
//  Created by steve on 15-1-6.
//  Copyright (c) 2015年 steve. All rights reserved.
//

#import "BOSSSoundWaveController.h"

#import "PayLayer.h"
#import "UIImage+Resize.h"
#import "CALayer+Util.h"
#import "SettingViewController.h"
#import "ASIFormDataRequest.h"
#import "commonDefines.h"
#import "JSONKit.h"

//static const char* const CODE_BOOK = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_@";

//static const char* const PLAY_STRING = "哈哈，居然可以传输中文";
#define TOKEN_COUNT 24

Class object_getClass(id object);

static Class _originalClass;

ESVoid onSinVoiceRecognizerStart(ESVoid* cbParam) {
   // NSLog(@"onSinVoiceRecognizerStart");
    Class currentClass = object_getClass((__bridge BOSSSoundWaveController*)cbParam);
    if (_originalClass == currentClass) {

        BOSSSoundWaveController* vc = (__bridge BOSSSoundWaveController*)cbParam;
        vc->mResultCount = 0;
    }
}

ESVoid onSinVoiceRecognizerToken(ESVoid* cbParam, ESInt32 index) {
    //NSLog(@"onSinVoiceRecognizerToken, index:%d", index);

    Class currentClass = object_getClass((__bridge BOSSSoundWaveController*)cbParam);
    if (_originalClass == currentClass) {
        
        BOSSSoundWaveController* vc = (__bridge BOSSSoundWaveController*)cbParam;
        vc->mResults[vc->mResultCount++] = index;
    }


}

ESVoid onSinVoiceRecognizerEnd(ESVoid* cbParam, ESInt32 result) {
    //NSLog(@"onSinVoiceRecognizerEnd, result:%d", result);
    Class currentClass = object_getClass((__bridge BOSSSoundWaveController*)cbParam);
    if (_originalClass == currentClass) {
        
        BOSSSoundWaveController* vc = (__bridge BOSSSoundWaveController*)cbParam;
        [vc onRecogToken:vc];
    }

  
}

ESVoid onSinVoicePlayerStart(ESVoid* cbParam) {
    //NSLog(@"onSinVoicePlayerStart, start");
    Class currentClass = object_getClass((__bridge BOSSSoundWaveController*)cbParam);
    if (_originalClass == currentClass) {
        BOSSSoundWaveController* vc = (__bridge BOSSSoundWaveController*)cbParam;
        [vc onPlayData:vc];
    }
   // NSLog(@"onPlayData, end");
}

ESVoid onSinVoicePlayerStop(ESVoid* cbParam) {
    //NSLog(@"onSinVoicePlayerStop");
    Class currentClass = object_getClass((__bridge BOSSSoundWaveController*)cbParam);
    if (_originalClass == currentClass) {
        BOSSSoundWaveController* vc = (__bridge BOSSSoundWaveController*)cbParam;
        
        if (vc.isStop) {
            return;
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [vc startPlay:nil];
        });
    } else {
        NSLog(@"exception");
    }
    
    
}

SinVoicePlayerCallback gSinVoicePlayerCallback = {onSinVoicePlayerStart, onSinVoicePlayerStop};
SinVoiceRecognizerCallback gSinVoiceRecognizerCallback = {onSinVoiceRecognizerStart, onSinVoiceRecognizerToken, onSinVoiceRecognizerEnd};

@interface BOSSSoundWaveController ()
@property (assign, nonatomic) kJoinResult joinResult;
@property (strong, nonatomic) PayLayer *pay;
@property (strong, nonatomic) SettingViewController *settingController;
@property (copy, nonatomic) NSString *receivedWaveStr;
@property (strong, nonatomic) ASIFormDataRequest *request;
@end
@implementation BOSSSoundWaveController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _originalClass = object_getClass(self);
    
    //voice
    mSinVoicePlayer = SinVoicePlayer_create("com.sinvoice.for.songwen", "SinVoice_For_Songwen", &gSinVoicePlayerCallback, (__bridge ESVoid *)(self));
    mSinVoiceRecorder = SinVoiceRecognizer_create("com.sinvoice.for.songwen", "SinVoice_For_Songwen", &gSinVoiceRecognizerCallback, (__bridge ESVoid *)(self));
    
    //初始化声波下面的引导信息
    [self initSoundWaveGuideView];
    
    //初始化confirm_view两个按钮边框
    _confirm_cancel_btn.layer.borderColor = HexRGB(0x676767).CGColor;
    _confirm_cancel_btn.layer.borderWidth = 1.0;
    _confirm_send_btn.layer.borderWidth = 1.0;
    _confirm_send_btn.layer.borderColor = HexRGB(0x29abe2).CGColor;
    
    if (!_isBoss) {
        [self setUpStaffWave];
    }
    [self showBOSS];
    if (_isBoss) {
        [self reset];
        
        NSLog(@"deliver == %@",[[NSUserDefaults standardUserDefaults] objectForKey:USER_SELECT_DELIVER]);
        
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:USER_SELECT_DELIVER] boolValue]==1 ||[[[NSUserDefaults standardUserDefaults] objectForKey:USER_SELECT_DELIVER] isEqualToString:@"true"]){
            //[self deliverBtnClicked:nil];
            _isDeliver = YES;
            _deliver_view.hidden = NO;
            _deliver_view1.hidden = YES;
            _collect_view.hidden = NO;
            _collect_view1.hidden = YES;
            [self hideOrShowSomeViews];
            
        }else{
            //[self collectBtnClicked:nil];
            _isDeliver = NO;
            _deliver_view.hidden = YES;
            _deliver_view1.hidden = NO;
            _collect_view.hidden = YES;
            _collect_view1.hidden = NO;
            [self hideOrShowSomeViews];
        }
    }
}

#pragma mark - ASIFormDataRequest

-(void)requestAsynchronouslyAction:(NSString *)action requestType:(NSInteger)type{
    
    NSString *urlString = [IPAddress stringByAppendingString:action];
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    _request = [ASIFormDataRequest requestWithURL:url];
    NSLog(@"request_url== %@",url);
    [_request buildRequestHeaders];
    [_request addRequestHeader:@"BasicAuthUsername" value:[[NSUserDefaults standardUserDefaults] objectForKey:GREEN_USER_ID]];
    if (type == ActionJoinGame || type == ActionStaffGetResult) {
//        _receivedWaveStr = @"abc";
        if ([_receivedWaveStr isEqualToString:@""]) {
            [self startRecord:nil];
            return;
        }
        [_request setPostValue:_receivedWaveStr forKey:@"gameId"];
    }
    if (type == ActionStartGame) {
        
        [_request setPostValue:[[NSUserDefaults standardUserDefaults] objectForKey:GREEN_SETTING_EACH] forKey:@"money"];
        [_request setPostValue:@"1" forKey:@"nums"];
    }
    if (type == ActionBossGetWinnerInfor) {
        //....
    }
    if (type == ActionSendOrCancel) {
        [_request setPostValue:_receivedWaveStr forKey:@"gameId"];
        if (_isSend) {
            [_request setPostValue:@"send" forKey:@"flag"];
        }else{
            [_request setPostValue:@"cancel" forKey:@"flag"];
        }
    }
    if (type == ActionEndGame) {
        [_request setPostValue:_waveStr forKey:@"soundId"];
    }
    [_request setTimeOutSeconds:10];
    _request.delegate = self;
    _request.tag = type;
    [_request startAsynchronous];
//    [self performSelector:@selector(cancelRequest) withObject:nil afterDelay:0.1];
}

#pragma mark  - ASIHTTPRequestDelegate

-(void)requestFinished:(ASIHTTPRequest *)request{
    
    NSString *responseString = request.responseString;
    NSMutableDictionary *dic = [responseString objectFromJSONString];
    if ([[dic objectForKey:@"code"] intValue] == -1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:[dic objectForKey:@"msg"] delegate:nil cancelButtonTitle:@"Ignore" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    if ([[dic objectForKey:@"code"] intValue] == 0) {
  
        //获取服务器信息
        NSDictionary *dataDic = [dic objectForKey:@"data"];
        
        if (request.tag == ActionStartGame) {
            DebugLog(@"Start game result: %@",dataDic);
            NSDictionary *data = [dataDic objectForKey:@"game"];
            
            //根据提示信息，更新UI
            if ((BOOL)[data objectForKey:@"notEnough"] == NO) {
                _isBalanceNotEnough = YES;
                [self initSoundWaveGuideView];
                _assist_view.hidden = YES;
                return;
            }
            if ([[data objectForKey:@"flag_hkd"] boolValue]== true || [[data objectForKey:@"flag_rmb"] boolValue]== true) {
                _isBalanceWarning = YES;
                [self initSoundWaveGuideView];
            }
            //预先初始化一下feedback_view
            if (_isBalanceWarning) {
                _feedback_warning_imageView.hidden = NO;
                _feedback_warning_label.hidden = NO;
                if ([[data objectForKey:@"location"] isEqualToString:@"CN"]) {
                    _feedback_warning_label.text = @"Your balance is less than RMB 100.";
                }else{
                    _feedback_warning_label.text = @"Your balance is less than HKD 100.";
                }
            }else{
                _feedback_warning_imageView.hidden = YES;
                _feedback_warning_label.hidden = YES;
            }
            
            _soundPlayDuration = [[data objectForKey:@"soundPlay"] integerValue];
            [[NSUserDefaults standardUserDefaults] setInteger:_soundPlayDuration forKey:@"progressDuration"];
            
            _bossRequestTimeOutDuration = [[data objectForKey:@"bossRequest"] integerValue];
            
            if (!_waveStr) {
                _waveStr = [[NSString alloc]init];
            }
            _waveStr = [NSString stringWithFormat:@"%d",[[data objectForKey:@"gameId"] integerValue]];
            NSLog(@"waveString==>%@",_waveStr);
            [self startAnimationAndPlay];
            
            //boss开始申请是否有人中奖
            [self requestAsynchronouslyAction:BossGetWinnerInfor requestType:ActionBossGetWinnerInfor];
        }
        if (request.tag == ActionBossGetWinnerInfor) {
            DebugLog(@"get winner info result: %@",dataDic);
            if([dataDic count] != 0){
                    _confirm_view.hidden = NO;
                    _confirm_userId_label.text = [dataDic objectForKey:@"userName"];
                    _sending_userId_label.text = [dataDic objectForKey:@"userName"];
                    //收到信息反馈之后停掉播放
                    [self onSending:nil];
                    [self onCatchWith:ActionBossGetWinnerInfor with:resultDraw];
            }
            if([dataDic count]== 0 && _isPlaying == YES){
                //如果老板没收到回应，过1秒钟继续申请
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    [self requestAsynchronouslyAction:BossGetWinnerInfor requestType:ActionBossGetWinnerInfor];
//                });
                [NSThread sleepForTimeInterval:1.0];
                [self requestAsynchronouslyAction:BossGetWinnerInfor requestType:ActionBossGetWinnerInfor];
            }
        }
        if (request.tag == ActionSendOrCancel) {
        
            if ([[dataDic objectForKey:@"sendOrCancel"] boolValue] == true) {
                //把indicator先停掉
                [self stopSendingIndicatorTimer];
                _sending_view.hidden = YES;
                _feedback_view.hidden = NO;
                [self performSelector:@selector(back) withObject:nil afterDelay:3];
            }
        }
        if (request.tag == ActionJoinGame) {
            DebugLog(@"jion game result: %@",dataDic);
            NSString *timeout = [dataDic objectForKey:STAFF_REQUEST_TIMEOUT];
            float staffTimeOut = [timeout integerValue];
            
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setFloat:staffTimeOut forKey:STAFF_REQUEST_TIMEOUT];
            [defaults synchronize];
            
            NSString *joinResult = [dataDic objectForKey:@"joinResult"];
            if ([joinResult isEqualToString:@"two"]) {
                _joinResult = resultTow;
                //NSInteger laiseeMoney = (NSInteger)[dataDic objectForKey:@"pageMoney"];
                
                //show note view
                [self onCatchWith:ActionJoinGame with:_joinResult];
            } else {
                if ([dataDic objectForKey:@"joinResult"]) {
                    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:[[NSUserDefaults standardUserDefaults] floatForKey:STAFF_REQUEST_TIMEOUT] target:self selector:@selector(stopStaffRequestTimer) userInfo:nil repeats:NO];
                    [self performSelector:@selector(startRecord:) withObject:nil afterDelay:[[NSUserDefaults standardUserDefaults] floatForKey:STAFF_REQUEST_TIMEOUT]];
                    
                    self.staffRequestTimer = timer;
                    
                    [self requestAsynchronouslyAction:StaffGetResult requestType:ActionStaffGetResult];
                    _isRequesting = YES;
                } else {
                    [self startRecord:nil];
                }
            }
        }
        if (request.tag == ActionStaffGetResult) {
            DebugLog(@"staff get result: %@",dataDic);
            if ([[dataDic objectForKey:@"joinResult"] isEqualToString:@""]) {
                if (_isRequesting) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self requestAsynchronouslyAction:StaffGetResult requestType:ActionStaffGetResult];
                    });
                }
            }
            
            if (![dataDic objectForKey:@"joinResult"]) {
                [self startRecord:nil];
            }
            
            if ([[dataDic objectForKey:@"joinResult"] isEqualToString:@"draw"]) {
                [self onCatchWith:ActionStaffGetResult with:resultDraw];
                [self performSelector:@selector(GoToMyLaisee) withObject:nil afterDelay:3];
            }
        }
        if (request.tag == ActionEndGame) {
            
            //收到结果，回复操作
            _assist_view.hidden = YES;
            
            _numOflaisee = [[dataDic objectForKey:@"game"] integerValue];
            [self onCatchWith:ActionEndGame with:resultNoDraw];
        }
    }
}
-(void)requestFailed:(ASIHTTPRequest *)request{
    NSError *error = [request error];
    
    NSLog(@"%@",[error.userInfo objectForKey:@"NSLocalizedDescription"]);
    NSLog(@"%@",[error localizedDescription]);
    
    if (request.tag == ActionStartGame) {
        _assist_view.hidden = YES;
    }
    if (request.tag == ActionSendOrCancel) {
        [self onSending:nil];
        [self back];
        _sending_view.hidden = YES;
    }
}

#pragma mark - Go To MyLaisees
-(void)GoToMyLaisee{
    [self.navigationController popViewControllerAnimated:YES];
    [self.hookWebViewController openMyLaisee];
}


#pragma mark - remove staff request timer

-(void)stopStaffRequestTimer{
    if (_staffRequestTimer) {
        [_staffRequestTimer invalidate];
        _staffRequestTimer = nil;
    }
    _isRequesting = NO;
}

#pragma mark - confirm_view button action
- (IBAction)confirmCancelAction:(id)sender {
    _isSend = NO;
    [self requestAsynchronouslyAction:SendOrCancel requestType:ActionSendOrCancel];
    //直接关闭
    [self back];
    _confirm_view.hidden = YES;
}

- (IBAction)confirmSendAction:(id)sender {
    _isSend = YES;
    [self requestAsynchronouslyAction:SendOrCancel requestType:ActionSendOrCancel];
    
    _confirm_view.hidden = YES;
    _sending_view.hidden = NO;
    [self addSendingIndicatorTimer];
}
#pragma mark - private
-(void)setUpStaffWave{
    [UIView animateWithDuration:0.5F
                     animations:^{
                         self.startButton.hidden = YES;
                         self.sendingButton.hidden = YES;
                         //[self addWaveTimer];
                         _actionGuide_label.text = @"Requesting a laisee...";
                         _actionGuide2_label.hidden = YES;
                         _settingButton.hidden = YES;
                         _warning_imageView.hidden = YES;
                         _warning_label.hidden = YES;
                         _deliver_view.hidden = YES;
                         _collect_view.hidden = YES;
                         _collect_view1.hidden = YES;
                         _deliver_view1.hidden = YES;
                         if (!_waveTimer) {
                             [self addStaffWaveTimer];
                         }
                         //staff 开始请求
                         [self startRecord:nil];
                         //[self requestAsynchronouslyAction:JoinGame requestType:ActionJoinGame];
                     }];
}
- (void)showBOSS {
    self.pay = [[PayLayer alloc] init];
    CGRect rect = self.pay.frame;
    rect.origin.x = (CGRectGetWidth([[UIScreen mainScreen] bounds]) - CGRectGetWidth(self.pay.frame)) * 0.5F;
    rect.origin.y = (CGRectGetHeight([[UIScreen mainScreen] bounds]) - CGRectGetHeight(self.pay.frame)) * 0.5F;
    self.pay.frame = rect;
    [self.background_view.layer insertSublayer:_pay
                                  atIndex:2];
    
}

- (void)changeSending {
    [UIView animateWithDuration:0.5F
                     animations:^{
                         self.collect_view.hidden = YES;
                         self.deliver_view.hidden = YES;
                         self.collect_view1.hidden = YES;
                         self.deliver_view1.hidden = YES;
                         self.startButton.hidden = YES;
                         self.sendingButton.hidden = NO;
                         [self addWaveTimer];
                         // 改变提示label信息
                         _actionGuide_label.text = @"Waiting for connection";
                         _actionGuide2_label.text = @"Tap to stop";
                     }];
}
- (void)reset {
    [UIView animateWithDuration:0.5F
                     animations:^{
                         self.collect_view.hidden = NO;
                         self.deliver_view.hidden = NO;
                         self.startButton.hidden = NO;
                         [self.startButton setImage:[UIImage imageNamed:@"green_button_start"] forState:UIControlStateNormal];
                         self.sendingButton.hidden = YES;
                         [self stopWaveTimer];
                         // 改变提示label信息
                         _actionGuide_label.text = @"Click now";
                         _actionGuide2_label.text = @"to give laisees";
                     }];
}
#pragma mark - add Timer to play "Boss Wave"
-(void)addWaveTimer{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(playSoundWave) userInfo:nil repeats:YES];
    [timer fire];
    self.waveTimer = timer;
}
-(void)playSoundWave{
    
    int temp = _waveCount%3;
    switch (temp) {
        case 0:
            [_sendingButton setImage:[UIImage imageNamed:@"green_button_boss_wave1"] forState:UIControlStateNormal];
            break;
        case 1:
            [_sendingButton setImage:[UIImage imageNamed:@"green_button_boss_wave2"] forState:UIControlStateNormal];
            break;
        case 2:
            [_sendingButton setImage:[UIImage imageNamed:@"green_button_boss_wave3"] forState:UIControlStateNormal];
            break;
        default:
            break;
    }
    _waveCount ++;
}
-(void)stopWaveTimer{
    [self.waveTimer invalidate];
    self.waveTimer = nil;
    _waveCount = 0;
    [_sendingButton setImage:[UIImage imageNamed:@"green_button_boss_sending"] forState:UIControlStateNormal];
}
#pragma mark - add Timer to play "staff Wave"
-(void)addStaffWaveTimer{
    _staff_wave_imageView.hidden = NO;
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(playStaffSoundWave) userInfo:nil repeats:YES];
    [timer fire];
    self.waveTimer = timer;
}
-(void)playStaffSoundWave{
    int temp = _waveCount%4;
    switch (temp) {
        case 0:
            _staff_wave_imageView.image = [UIImage imageNamed:@"green_staff_wave1"];
            break;
        case 1:
            _staff_wave_imageView.image = [UIImage imageNamed:@"green_staff_wave2"];
            break;
        case 2:
            _staff_wave_imageView.image = [UIImage imageNamed:@"green_staff_wave3"];
            break;
        case 3:
            _staff_wave_imageView.image = [UIImage imageNamed:@"green_staff_wave4"];
            break;
        default:
            break;
    }
    _waveCount ++;
}
-(void)stopStaffWaveTimer{
    [self.waveTimer invalidate];
    self.waveTimer = nil;
    _waveCount = 0;
    _staff_wave_imageView.image = [UIImage imageNamed:@"green_staff_wave1"];
    _staff_wave_imageView.hidden = YES;
}
#pragma mark - add Timer to play "indicator"
-(void)addSendingIndicatorTimer{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(playStaffSoundWave) userInfo:nil repeats:YES];
    [timer fire];
    self.indicatorTimer = timer;
}
-(void)playSendingIndicator{
    int temp = _waveCount%8;
    switch (temp) {
        case 0:
            _sending_indicator_imageView.image = [UIImage imageNamed:@"sending_indicator_image1"];
            break;
        case 1:
            _sending_indicator_imageView.image = [UIImage imageNamed:@"sending_indicator_image2"];
            break;
        case 2:
            _sending_indicator_imageView.image = [UIImage imageNamed:@"sending_indicator_image3"];
            break;
        case 3:
            _sending_indicator_imageView.image = [UIImage imageNamed:@"sending_indicator_image4"];
            break;
        case 4:
            _sending_indicator_imageView.image = [UIImage imageNamed:@"sending_indicator_image5"];
            break;
        case 5:
            _sending_indicator_imageView.image = [UIImage imageNamed:@"sending_indicator_image6"];
            break;
        case 6:
            _sending_indicator_imageView.image = [UIImage imageNamed:@"sending_indicator_image7"];
            break;
        case 7:
            _sending_indicator_imageView.image = [UIImage imageNamed:@"sending_indicator_image8"];
            break;
        default:
            break;
    }
    _waveCount ++;
}
-(void)stopSendingIndicatorTimer{
    [self.indicatorTimer invalidate];
    self.indicatorTimer = nil;
    _waveCount = 0;
}
#pragma mark - action
- (void)onCatchWith:(kRequestAction)actionType with:(kJoinResult)resultType{

    UIImage *catch = [self.background_view.layer toImage];
    _show.image = [catch croppedImage:CGRectMake(0, 0, catch.size.width, catch.size.height * 0.5F)];
    _show2.image = [catch croppedImage:CGRectMake(0, catch.size.height * 0.5F, catch.size.width, catch.size.height * 0.5F)];
    _show.hidden = NO;
    _show2.hidden = NO;
    if (actionType == ActionJoinGame) {
        [self startRecord:nil];

        _receive_oops_view.hidden = NO;
        _oops_note_label.text = @"You can only collect one laisee from the same distributor.";
        [self performSelector:@selector(addAnimationThenReback)];
    }
    if (actionType == ActionBossGetWinnerInfor) {
        //.....
        
        [self replaceTopConstraintOnView:_show withConstant:-90];
        [self replaceBottomConstraintOnView:_show2 withConstant:-90];
        [self animateConstraints];
    }
    if (actionType == ActionStaffGetResult) {
        _receive_cong_view.hidden = NO;
        [self stopStaffRequestTimer];
        [self performSelector:@selector(addAnimationThenReback)];
        [self startRecord:nil];

    }
    if (actionType == ActionEndGame) {

        [self addAnimationThenReback];
    }
}
#pragma mark - open and close
-(void)addAnimationThenReback{
    [self replaceTopConstraintOnView:_show withConstant:-90];
    [self replaceBottomConstraintOnView:_show2 withConstant:-90];
    [self animateConstraints];
    [self performSelector:@selector(back) withObject:nil afterDelay:3];
}
#pragma mark - hidden show view
-(void)back{
    _confirm_view.hidden = YES;
    _feedback_view.hidden = YES;
    _receive_oops_view.hidden = YES;
    _receive_cong_view.hidden = YES;
    _show.hidden = YES;
    _show2.hidden = YES;
    [self replaceTopConstraintOnView:_show withConstant:0];
    [self replaceBottomConstraintOnView:_show2 withConstant:0];
    [self animateConstraints];
}
- (IBAction)onStart:(id)sender {

    if ([[NSUserDefaults standardUserDefaults] objectForKey:GREEN_SETTING_EACH] == nil ) {
        if (!_settingController) {
            _settingController = [[SettingViewController alloc]initWithNibName:@"SettingViewController" bundle:nil];
        }
        self.settingController.view.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetHeight([UIScreen mainScreen].bounds));
        [self.view addSubview:self.settingController.view];
        _assist_view.hidden = YES;
        return;
    }
    _assist_view.hidden = NO;
    [self requestAsynchronouslyAction:StartGame requestType:ActionStartGame];

}
-(void)startAnimationAndPlay{
    
    //设置播放状态，作为后台循环请求标志
    _isPlaying = YES;
    
    //soundPlayDuration 过后停止播放 “声波和外圈动画”
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:(_soundPlayDuration) target:self selector:@selector(endPlaySound) userInfo:nil repeats:NO];
    self.endPlayTimer = timer;
    
    //soundPlayDuration+bossRequestTimeOutDuration 过后停止“内圈动画”
    NSTimer *aTimer = [NSTimer scheduledTimerWithTimeInterval:(_soundPlayDuration+_bossRequestTimeOutDuration) target:self selector:@selector(endGame) userInfo:nil repeats:NO];
    self.endGameTimer = aTimer;
    
    _startButton.enabled = NO;
    [self changeSending];
    
    [self.pay play];
    //播放声波
    [self startPlay:nil];
    _startButton.enabled = YES;
    _assist_view.hidden = YES;
}
-(void)endPlaySound{
    //停外圈动画
    [self.pay stop];
    //停声波
    [self stopPlay:nil];
    
    if (_endPlayTimer) {
        [_endPlayTimer invalidate];
        _endPlayTimer = nil;
    }
}
-(void)endGame{
    
    //game结束
    _isPlaying = NO;
    
    //如果在soundPlayDuration+bossRequestTimeOutDuration内还是没有得到回应
    [UIView animateWithDuration:0.5F
                     animations:^{
                         self.startButton.hidden = NO;
                         [self.startButton setImage:[UIImage imageNamed:@"green_button_retry"] forState:UIControlStateNormal];
                         _actionGuide_label.text = @"Retry again";
                         _actionGuide2_label.text = @"to give laisees";
                     }];
    self.sendingButton.hidden = YES;
    [self stopWaveTimer];

    if (_endGameTimer) {
        [_endGameTimer invalidate];
        _endGameTimer = nil;
    }
}
- (IBAction)onSending:(id)sender {
    
//    //点击暂停，等待回馈，此时不能继续操作
//    _assist_view.hidden = NO;
    
    //点击暂停，game结束
    _isPlaying = NO;
    
    //一旦点击暂停，Game结束，取消定所有时器
    if (_endGameTimer) {
        [_endGameTimer invalidate];
        _endGameTimer = nil;
    }
    if (_endPlayTimer) {
        [_endPlayTimer invalidate];
        _endPlayTimer = nil;
    }
    ((UIButton *)sender).enabled = NO;
    [self reset];
    [self.pay stop];
    //暂停声波
    [self stopPlay:nil];
    ((UIButton *)sender).enabled = YES;
    
    //[self requestAsynchronouslyAction:EndGame requestType:ActionEndGame];
}

- (IBAction)onHome:(id)sender {
    
    ((UIButton *)sender).enabled = NO;
    
//    if (!_isDeliver) {
//        [self stopStaffRequestTimer];
//    }else{
//        [self onSending:nil];
//    }
    //如果在录音的话 先停掉
    [self stopRecord:nil];
    //staff界面必须要停掉内圈播放动画
    [self stopStaffRequestTimer];
    //如果boss在播放声波时，一定要先停掉
    [self onSending:nil];
    //取消掉一切请求
    if (_request) {
        [_request cancel];
//        _request = nil;
    }
    
//    [self dismissViewControllerAnimated:YES
//                             completion:^{
//                                 
//                             }];
    [self.navigationController popViewControllerAnimated:YES];
    ((UIButton *)sender).enabled = YES;
}
- (IBAction)settingsBtnClicked:(id)sender {
    
    if (!_settingController) {
        self.settingController = [[SettingViewController alloc]initWithNibName:@"SettingViewController" bundle:nil];
    }
    self.settingController.view.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetHeight([UIScreen mainScreen].bounds));
    [self.view addSubview:self.settingController.view];
}
-(void)initSoundWaveGuideView{
    
    NSString *locStr;
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:GREEN_USER_LOCATION] isEqualToString:@"CN"]) {
        locStr = @"RMB";
    }else{
        locStr = @"HKD";
    }

    //show
    _warning_label.hidden = NO;
    _warning_imageView.hidden = NO;

    if (!_isBalanceNotEnough && !_isBalanceWarning) {
        _warning_label.hidden = YES;
        _warning_imageView.hidden = YES;
        return;
    }
    if (_isBalanceWarning) {
        _warning_imageView.image = [UIImage imageNamed:@"green_image_note"];
        _warning_label.text = [NSString stringWithFormat:@"Your balance is less than %@ 100.",locStr];
        _warning_label.textColor = RGBAlpha(247, 147, 30, 1);
    }
    if (_isBalanceNotEnough) {
        _warning_imageView.image = [UIImage imageNamed:@"green_image_warning"];
        _warning_label.text = @"You do not have enough balance.";
        _warning_label.textColor = RGBAlpha(200, 0, 1, 1);
    }
    
}

#pragma mark - Animation Methods

- (void)replaceTopConstraintOnView:(UIView *)view withConstant:(float)constant
{
    [self.view.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
        if ((constraint.firstItem == view) && (constraint.firstAttribute == NSLayoutAttributeTop)) {
            constraint.constant = constant;
        }
    }];
}
- (void)replaceBottomConstraintOnView:(UIView *)view withConstant:(float)constant
{
    [self.view.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
        if ((constraint.firstItem == view.superview) && (constraint.firstAttribute == NSLayoutAttributeBottom) && (constraint.secondItem == view)) {
            constraint.constant = constant;
        }
    }];

}
- (void)animateConstraints
{
    [UIView animateWithDuration:0.5 animations:^{
        [self.view layoutIfNeeded];
    }];
}

#pragma mark - exchange Collect And Deliver Button -
- (IBAction)collectBtnClicked:(id)sender {
    if (!_isDeliver) {
        return;
    }else{
        _isDeliver = NO;
//        [_buttons_view bringSubviewToFront:_collect_view];
//        [_collect_btn setImage:[UIImage imageNamed:@"green_button_cloud_big"] forState:UIControlStateNormal];
//        _collect_label.textColor = HexRGB(0x676767);
//        _deliver_label.textColor = HexRGB(0x29abe2);
        _deliver_view.hidden = YES;
        _deliver_view1.hidden = NO;
        _collect_view.hidden = YES;
        _collect_view1.hidden = NO;
        [self hideOrShowSomeViews];
    }
    
//    [self.HTMLView stringByEvaluatingJavaScriptFromString:@"Hsbc.mobile.app.pageTransition(file:///web/postlogon/menu/menu.html)"];
//    [self.HTMLView stringByEvaluatingJavaScriptFromString:@"file:///web/postlogon/menu/menu.html"];

}

- (IBAction)deliverBtnClicked:(id)sender {
    if (_isDeliver) {
        return;
    }else{
        _isDeliver = YES;
//        [_buttons_view bringSubviewToFront:_deliver_view];
//        
//        _deliver_label.textColor = HexRGB(0x676767);
//        _collect_label.textColor = HexRGB(0x29abe2);
        _deliver_view.hidden = NO;
        _deliver_view1.hidden = YES;
        _collect_view.hidden = NO;
        _collect_view1.hidden = YES;
        [self hideOrShowSomeViews];
    }
}

#pragma  mark - According Actions to Show or Hide views
-(void)hideOrShowSomeViews{
    if(_isDeliver){
        _round_imageView.hidden = YES;
        _startButton.hidden = NO;
        _sendingButton.hidden = YES;
        _staff_wave_imageView.hidden = YES;
        _actionGuide_label.text = @"Click now";
        _actionGuide2_label.hidden = NO;
//        _warning_label.hidden = NO;
//        _warning_imageView.hidden = NO;
        _settingButton.hidden = NO;
        if (_waveTimer) {
            [self stopStaffWaveTimer];
            //如果在录音先停掉
            [self stopRecord:nil];
            if (_request) {
                [_request cancel];
                _request = nil;
            }
        }
    }else{
        if (_waveTimer) {
            [self stopWaveTimer];
            [self onSending:nil];
        }
        _round_imageView.hidden = NO;
        _startButton.hidden = YES;
        _sendingButton.hidden = YES;
        _staff_wave_imageView.hidden = NO;
        _actionGuide_label.text = @"Requesting a laisee...";
        _actionGuide2_label.hidden = YES;
        _warning_label.hidden = YES;
        _warning_imageView.hidden = YES;
        _settingButton.hidden = YES;
        [self addStaffWaveTimer];
        [self startRecord:nil];
    }
}
#pragma mark - Voice -

-(void)onPlayData:(BOSSSoundWaveController*)data
{
//    NSThread* curThrd =[NSThread currentThread];
//    NSLog(@"onPlayData, thread:%@",curThrd);
    [self performSelectorOnMainThread:@selector(updateUI:) withObject:data waitUntilDone:FALSE];
}

-(void)updateUI:(BOSSSoundWaveController*)data
{
//    NSThread* curThrd =[NSThread currentThread];
//    NSLog(@"updateUI, thread:%@",curThrd);
    
    char ch[100] = { 0 };
    for ( int i = 0; i < mPlayCount; ++i ) {
        ch[i] = (char)data->mRates[i];
    }
}

-(void)onRecogToken:(BOSSSoundWaveController*)data
{
//    NSThread* curThrd =[NSThread currentThread];
//    NSLog(@"onRecordData, thread:%@",curThrd);
    [self performSelectorOnMainThread:@selector(updateRecordUI:) withObject:data waitUntilDone:FALSE];
}

-(void)updateRecordUI:(BOSSSoundWaveController*)data
{
//    NSThread* curThrd =[NSThread currentThread];
//    NSLog(@"updateUI, thread:%@",curThrd);
    
    char ch[100] = { 0 };
    for ( int i = 0; i < mResultCount; ++i ) {
        ch[i] = (char)data->mResults[i];
    }
    
    NSString* str = [NSString stringWithCString:ch encoding:NSUTF8StringEncoding];
    NSLog(@"Received string = %@",str);
    _receivedWaveStr = [[NSString alloc]initWithString:str];
    [self requestAsynchronouslyAction:JoinGame requestType:ActionJoinGame];
    [self stopRecord:nil];
}

- (void)startPlay:(UIButton *)sender {
    
    self.isStop = NO;
    int index = 0;
    if (_waveStr == nil) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"Sound wave string should not be nil." delegate:nil cancelButtonTitle:@"I know!" otherButtonTitles:nil];
        [alert show];
    }
    NSString* xx = _waveStr;
    const char* str = [xx cStringUsingEncoding:NSUTF8StringEncoding];
    
    mPlayCount = (int)strlen(str);
    while ( index < mPlayCount) {
        mRates[index] = str[index];
        ++index;
    }
    SinVoicePlayer_play(mSinVoicePlayer, mRates, mPlayCount);
}

- (void)stopPlay:(UIButton *)sender {
    
    _isStop = YES;
    SinVoicePlayer_stop(mSinVoicePlayer);
    SinVoicePlayer_stop(mSinVoicePlayer);

}

- (void)startRecord:(UIButton *)sender {

    SinVoiceRecognizer_start(mSinVoiceRecorder, TOKEN_COUNT);
}

- (void)stopRecord:(UIButton *)sender {

    SinVoiceRecognizer_stop(mSinVoiceRecorder);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//- (void) payIt {
//    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:nil];
//    [request setCompletionBlock:^{
//        NSLog(@"%@", request.responseString);
//    }];
//    [request setFailedBlock:^{
//        // hook error
//        
//    }];
//    [request startAsynchronous];
//}


@end
